package com.java.activiti.controller;

import com.java.activiti.service.ActivityCommonService;
import com.java.activiti.util.CommonResponse;
import com.sun.deploy.net.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.EndEventXMLConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * ${applyWorker} 启动实例的时候给到值

 ${applyMangerAduilt}  任务办理时设置

 ${applyDays>4}  通过当前流程实例设置、

 ${applyHumanHR} 通过当前任务设置
 */

/**
 * @Company: PcGroup.ltd
 * @Author: wei.ye
 * @Date: 2021/1/12 16:45
 * @Modified:2021/1/12 16:45
 * @Description:  activity学习之global和local的流程变量的设置
 */
@Slf4j
@RestController
@RequestMapping("/applyVocation")
public class ApplyVocationController {
    @Autowired
    private ActivityCommonService activityCommonService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    //部署
    @RequestMapping("/deploy")
    public Object deploy(HttpServletResponse response){
        Deployment deploy=null;
        try {
            InputStream in = ApplyVocationController.class.getClassLoader().getResourceAsStream("activiti/employee_applyVocation.zip");
            ZipInputStream inputStream=new ZipInputStream(in);
            String text="employee_applyVocation流程";
            String category="vocation";
            deploy = activityCommonService.deploy(inputStream, "员工请假流程申请", "employee_applyVocation", text, category);
        } catch (Exception e){
            return  e.getMessage();
        }
        return deploy;
    }

    //start一个process
    @RequestMapping("/start")
    public Object startProcess(){
        //start的时候模拟动态加入任务的负责人
        Deployment deployment = activityCommonService.createDeploymentQueryByName("employee_applyVocation", "", "");
        Map<String,Object> paramas=new HashMap<String, Object>(10);
        paramas.put("applyWorker", "尹成");
        ProcessInstance processInstance = activityCommonService.startProcessInstanceWithId(deployment.getId(), paramas);
        return CommonResponse.JSONString(200, processInstance);
    }

    //完成任务 的时候设置流程变量
    @RequestMapping(value = "/completeTasksetvarabiles",produces="text/html;charset=UTF-8;")
    public String completeTask(HttpServletResponse response, HttpServletRequest request,@RequestParam(required = true,defaultValue = "") String assignee) throws Exception{

        StringBuilder sb=new StringBuilder(10);
        if (StringUtils.isEmpty(assignee)) {
            return  sb.append("{statusCode:500,msg:assignee参数不能为空}").toString();
        }
        //使用部署时第一步的办理人的名字来查询任务
        sb.append("{")    ;
        String processDefinationKey="employee_applyVocation_processID";
        ProcessDefinition processDefination = activityCommonService.getCurrentProcessDefination(processDefinationKey);
        List<Task> currentTaskInstanceList = activityCommonService.getCurrentTaskInstance(processDefination.getId(), "尹成");
        for (Task task: currentTaskInstanceList
                ) {
            sb.append(task.getId()+","+task.getProcessDefinitionId()+","+task.isSuspended()+","+task.getProcessInstanceId()).append(","+task.getName()+","+task.getTaskDefinitionKey());
            //完成任务
            Map<String,Object> paramas=new HashMap<String, Object>(5);
            paramas.put("applyMangerAduilt", "杨过");
            taskService.complete(task.getId(),paramas);
        }
        return  sb.append("}").toString();
    }

    //通过当前流程实例设置：部门经理审核 传递local实例变量    runtimeService.setVariable(executionId, "holiday", holiday);
    @RequestMapping(value = "/completeWithRuntimeVariable",produces = "text/html;charset=UTF-8;")
    public Object completeWithRuntimeVariable(HttpServletRequest request,HttpServletResponse response,
                                              @RequestParam(defaultValue ="0",required = true) String dayNum){
        //applyMangerAduilt=杨过 已经传递值
        int days = Integer.parseInt(dayNum);
        //获得当前处理人的任务：正在执行的任务
        String assignee="杨过";
        Map<String,Object> queryParas=new HashMap<String, Object>(5);
        queryParas.put("processDefinationKey", "employee_applyVocation_processID");
        queryParas.put("assignee", assignee);
        List<Task> tasks = activityCommonService.findUniqueRuntimeTaskByAssigneeAndprocessDefinationKey(queryParas);
        //设置变量
        for (Task task:tasks
                ) {
            //通过流程实例id设置全局变量，该流程实例必须未执行完成
            runtimeService.setVariable(task.getExecutionId(), "applyDays", days);
            taskService.addComment(task.getId(), task.getProcessInstanceId(), "经理审批完成. time="+new Date(System.currentTimeMillis()));
            Map<String,Object> varaibles=new HashMap<String, Object>(4);
            if(days>4) {
                String highlevelManger = "周伯通";
                varaibles.put("highlevelManger", highlevelManger);
                String applyHumanHR = "谷大师";
                varaibles.put("applyHumanHR", applyHumanHR);
            }
            taskService.complete(task.getId(),varaibles);
        }
        return "审批完成...";
    }

    //总经理审批
    @RequestMapping("/highlevelMangerAduilt")
    public Object highlevelMangerAduilt(HttpServletResponse response,HttpServletRequest request){
        //获得当前自己的任务
        StringBuilder sb=new StringBuilder(10);
        String assignee="周伯通";
        Map<String,Object> queryParas=new HashMap<String, Object>(5);
        queryParas.put("processDefinationKey", "employee_applyVocation_processID");
        queryParas.put("assignee", assignee);
        List<Task> tasks = activityCommonService.findUniqueRuntimeTaskByAssigneeAndprocessDefinationKey(queryParas);
        //完成任务
        complete(sb, tasks,"总经理审核通过");
        return  sb.toString();
    }

    //hr审批
    @RequestMapping("/hrAduilt")
    public Object hrAuduilt(HttpServletRequest request,HttpServletResponse response){
        //获得当前自己的任务
        StringBuilder sb=new StringBuilder(10);
        String assignee="谷大师";
        Map<String,Object> queryParas=new HashMap<String, Object>(5);
        queryParas.put("processDefinationKey", "employee_applyVocation_processID");
        queryParas.put("assignee", assignee);
        List<Task> tasks = activityCommonService.findUniqueRuntimeTaskByAssigneeAndprocessDefinationKey(queryParas);
        complete(sb, tasks,"人事经理 谷大师审核通过啦");
        return  sb.toString();
    }

    @RequestMapping("/test")
    public String test(){
        return "我爱de林允儿啊...";
    }

    //完成任务
    private void complete(StringBuilder sb, List<Task> tasks,String comment) {
        if(tasks.size()>0){
            for (Task  task:tasks
                    ) {
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment+""+new Date());
                log.info("[{taskid:"+task.getId()+",taskname:"+task.getName()+",assignee："+task.getAssignee()+"act_id:"+task.getTaskDefinitionKey()+"}]");
                sb.append("[{taskid:"+task.getId()+",taskname:"+task.getName()+",assignee："+task.getAssignee()+"act_id:"+task.getTaskDefinitionKey()+"}]");
                taskService.complete(task.getId());
            }
        }
    }
}